from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet  # 视图集模块
from .serializers import *  # 所有的序列化器类
from rest_framework.permissions import IsAuthenticated  # 是否登录权限管理
from utils.permission import TeacherPermission  # 老师权限
# Create your views here.

from rest_framework.decorators import action  # 行为路由装饰器
from rest_framework.response import Response  # 响应
from rest_framework.status import HTTP_404_NOT_FOUND,HTTP_201_CREATED,HTTP_204_NO_CONTENT
import random,string
from django.contrib.auth.models import Group  # 组
from celery_tasks.email.tasks import send_email_task

# 班级的视图集
class ClassesViewSet(ModelViewSet):
    queryset = Classes.objects.filter(is_delete=False)  # 查询集
    serializer_class = ClassesSerializer  # 需要使用的序列化器
    # 要求用户先进行身份验证，才能够访问该视图类
    # permission_classes = [IsAuthenticated]
    # 要求是老师，才可看班级的路由页面
    # permission_classes = [TeacherPermission]

    # 根据不同的行为使用不同的序列化器
    def get_serializer(self, *args, **kwargs):
        if self.action == 'students':
            return CreateUserSerializer(*args,**kwargs)
        return self.serializer_class(*args,**kwargs)

    # 自定义视图集方法
    @action(methods=['post'],detail=True)  # 访问
    def students(self,request,pk):
        try:
            classes = self.get_queryset().get(id=pk)  # 哪个班
        except Classes.DoesNotExist:  # 没获取到数据
            return Response(status=HTTP_404_NOT_FOUND)

        # 前端传入的数据
        username = request.data['username']
        email = request.data['email']
        first_name = request.data['first_name']

        # 查询注册的用户是否在该班级
        member = classes.member.filter(username=username)
        if member:
            return Response({'msg':'该学员已加入该班级'})
        # 在用户表当中，有没有注册的这个学员
        user = User.objects.filter(username=username)
        if user:
            user = user.first()
            classes.member.add(user)  # 向班级添加该学员
            return Response(self.get_serializer(user).data)

        # 不存在该用户，创建
        user_serializer = self.get_serializer(data=request.data)  # 反序列化
        user_serializer.is_valid(raise_exception=True)
        # 向模型写入数据
        user = User(username=username,email=email,first_name=first_name)
        # 密码
        source = string.ascii_letters + string.digits
        password = ''.join(random.sample(source, 6))  # qwe123
        # 加密
        user.set_password(password)
        user.save() # 保存

        # 安排在学生组当中
        group = Group.objects.get(id=2)
        group.user_set.add(user)
        # 向班级添加该学生
        classes.member.add(user)

        # 简单模拟邮箱发送
        # print(email,username,password,classes.name)
        send_email_task.delay(email,username,password,classes.name)

        return Response(user_serializer.data,status=HTTP_201_CREATED)
